package com.mzj.saas.commons.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.*;
import java.util.Calendar;
import java.util.Date;

public class ConvertUtils
{
	public static final short str2short(String str)
	{
		if (str == null || str.isEmpty())
			return 0;
		try
		{
			return Short.parseShort(str);
		}
		catch (Exception err)
		{
			return 0;
		}
	}
	
	public static final int str2int(String str)
	{
		if (str == null || str.isEmpty())
			return 0;
		try
		{
			return Integer.parseInt(str);
		}
		catch (Exception err)
		{
			return 0;
		}
	}

	public static final long str2long(String str)
	{
		if (str == null || str.isEmpty())
			return 0;
		try
		{
			return Long.parseLong(str);
		}
		catch (Exception err)
		{
			return 0;
		}
	}

	public static final double str2double(String str)
	{
		if (str == null || str.isEmpty())
			return 0;
		try
		{
			return Double.parseDouble(str);
		}
		catch (Exception err)
		{
			return 0;
		}
	}

	public static final float str2float(String str)
	{
		if (str == null || str.length() <= 0)
			return 0;
		try
		{
			return Float.parseFloat(str);
		}
		catch (Exception err)
		{
			return 0;
		}
	}

	public static final boolean str2boolean(String str)
	{
		if( str == null || str.isEmpty() )
			return false ;
		
		char firstChar = Character.toLowerCase(str.charAt(0)) ;
		if ('1' == firstChar || 't' == firstChar || 'y' == firstChar )
			return true;
		else
			return false;
	}

	public static final byte[] str2ipaddr(String src)
	{
		int count = StringUtils.count( src, '.' ) ;
		if( count == 4 )
			return IpAddressUtils.textToNumericFormatV4(src) ;
		else
			return IpAddressUtils.textToNumericFormatV6(src) ;
	}

	public static String ipaddr2str(byte[] addr)
	{
		StringBuilder buf = new StringBuilder();
		if( addr.length == 4 )
		{
		for (int i = 0; i < addr.length; i++)
		{
			buf.append(addr[i] & 0xFF);
			if (i < addr.length - 1)
				buf.append(".");
		}
		}
		else
		{
			int len = 8;
			for (int i = 0; i < len; i++)
			{
				buf.append(Integer.toHexString(((addr[i << 1] << 8) & 0xff00) | (addr[(i << 1) + 1] & 0xff)));
				if (i < len - 1)
					buf.append(":");
			}
		}
		
		return buf.toString();
	}
	
	private static final ThreadLocal<DateFormat> dateFormatterTlv = new ThreadLocal<>() ;
	private static final ThreadLocal<Calendar> calendarTlv = new ThreadLocal<>() ;
	
	public static final String date2str(Date time)
	{
		DateFormat formatter = dateFormatterTlv.get() ;
		if( formatter == null )
		{
			formatter = new SimpleDateFormat("yyyyMMddHHmmss") ;
			dateFormatterTlv.set( formatter );
		}
		
		return formatter.format(time);
	}
	
	public static final String date2str(long millis)
	{
		Calendar calendar = calendarTlv.get() ;
		if( calendar == null )
		{
			calendar = Calendar.getInstance() ;
			calendarTlv.set( calendar );
		}
		
		calendar.setTimeInMillis(millis);
		return date2str( calendar.getTime() ) ;
	}
	
	/**
	 * 分转换成元 保留2位小数
	 * @param fen
	 * @return
	 */
	public static String fenConvertYuan(Integer fen) {
		return fen == null || fen == 0 ? "0.00" : (new BigDecimal(fen).divide(new BigDecimal("100")).setScale(2)).toString();
	}

	/**
	 * 分转元（四舍五入，保留2位小数）
	 *
	 * @param fen
	 * @return 字符串，如：“0.00”、“0.10”
	 * @author chensenrong
	 */
	public static String fenConvertYuan(Long fen) {
		if (fen == null || fen == 0) {
			return "0.00";
		}

		BigDecimal divide = new BigDecimal(fen).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
		DecimalFormat decimalFormat = new DecimalFormat("0.00#");
		return decimalFormat.format(divide);
	}

	/**
	 * 分转元（四舍五入，保留2位小数）
	 *
	 * @param fen
	 * @return
	 * @author chensenrong
	 */
	public static BigDecimal fen2yuan(Integer fen) {
		return fen == null || fen == 0 ? BigDecimal.ZERO
				: new BigDecimal(fen).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
	}

	/**
	 * 分转元（四舍五入，保留2位小数）
	 *
	 * @param fen
	 * @return
	 * @author chensenrong
	 */
	public static BigDecimal fen2yuan(Long fen) {
		return fen == null || fen == 0 ? BigDecimal.ZERO
				: new BigDecimal(fen).divide(new BigDecimal("100"), 2, RoundingMode.HALF_UP);
	}

	/**
	 * 元转分
	 *
	 * @param yuan 元，两位小数以内
	 * @return
	 * @author chensenrong
	 */
	public static int yuan2fen(BigDecimal yuan) {
		return yuan == null ? 0 : yuan.multiply(new BigDecimal("100")).intValue();
	}

	/*
	 *分转换为元
	 */
	public static String fenToYuan(String amount) {
		NumberFormat format = NumberFormat.getInstance();
		try {
			Number number = format.parse(amount);
			double temp = number.doubleValue() / 100.0;
			format.setGroupingUsed(false);
			// 设置返回的小数部分所允许的最大位数
			format.setMaximumFractionDigits(2);
			amount = format.format(temp);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return amount;
	}

	/*
	 *元转换为分
	 */
	public static String yuanToFen(String amount) {
		NumberFormat format = NumberFormat.getInstance();
		try {
			Number number = format.parse(amount);
			double temp = number.doubleValue() * 100.0;
			format.setGroupingUsed(false);
			// 设置返回数的小数部分所允许的最大位数
			format.setMaximumFractionDigits(0);
			amount = format.format(temp);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return amount;
	}
}
